<template>
  <el-scrollbar class="message-group-box" ref="refScrollbar" @scroll="scrollHandle">
    <div ref="refInner">
      <div class="tips">
        <el-icon v-show="loading"><Loading /></el-icon>
        <p v-show="!loading && list.length >= page.total">暂无更多</p>
      </div>
      <message
        v-show="!loading"
        v-for="(item, index) in list"
        :key="index"
        :data="item"
        class="message"
      />
    </div>
  </el-scrollbar>
</template>
<script setup>
import { onMounted, computed, watch, ref, reactive, nextTick } from 'vue'
import { useStore } from "vuex"
import Message from './message.vue'
const store = useStore()
const friend = computed(() => store.state.conversation.active || {})
const scrollBottom = computed((() => store.state.message.scrollBottom))
const list = computed(() => store.state.message.privateMessages)
const loading = ref(false)
const page = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
})
const refScrollbar = ref(null)
const refInner = ref(null)
onMounted(() => {
  getMessage(true)
})

const getMessage = async (clear) => {
  loading.value = true
  if(clear) {
    page.pageNum = 1
    page.total = 0
    page.pages = 1
  }
  console.log(friend.value, "friend.value")
  let params = {
    pageNum: page.pageNum,
    pageSize: page.pageSize,
    conversationId: friend.value.conversationId,
    // userId: friend.value.id,
    times: store.state.message.privateMessages.length && !clear ? store.state.message.privateMessages[store.state.message.privateMessages.length - 1].createTime : ''
  }

  const res = await store.dispatch("message/getPrivateMessages", {params, clear})
  if(res) {
    loading.value = false
    if(clear) {
      store.dispatch("message/updateScrollBottom")
    }
    page.total = res.data.total
  }
  return res

}
/**
 * 滚动条事件 滚动到顶部
 */
const scrollHandle = ({ scrollTop }) => {
  const height = refInner.value.clientHeight
  if (!loading.value && scrollTop === 0 && list.value.length < page.total) {
    page.pageNum++
    getMessage(false).then(r => {
      if (r) {
        nextTick(() => {
          refScrollbar.value.setScrollTop(refInner.value.clientHeight - height)
        })
      }
    })
  }
}

watch(() => scrollBottom.value, () => {
  nextTick(() => {
    refScrollbar.value.setScrollTop(refInner.value.clientHeight)
  })
})

watch(() => friend.value, (newVal, _oldVal) => {
  if (newVal) {
    getMessage(true)
  }
}, { deep: true })

</script>

<style lang="scss" scoped>
.message-group-box {
  padding: 0 10px;
  flex: 1;
}
.tips {
  width: 100%;
  text-align: center;
  font-size: 12px;
  color: $darkColor-6;
  display: block;
  margin: 10px 0;
}
.message {
  margin: 20px 0;
}
</style>
